#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <vector>

const int num = 10;

void *routine(void *args)
{
    std::string name = static_cast<const char *>(args);
    delete (char *)args; // 回收掉拷贝的空间
    int cnt = 5;
    while (cnt--)
    {
        std::cout << "新线程名字: " << name << pthread_self() <<  std::endl;
        sleep(1);
    }
    // sleep(1);
    return nullptr;
}

int main()
{
    // 创建10个线程
    std::vector<pthread_t> tids;
    for (int i = 0; i < num; i++)
    {
        pthread_t tid;
        // char id[64];  不行，会导致数据传入新线程的地址相同，数据不一致，安全性降低
        char *id = new char[64]; // 每次开一块空间，id传到新线程时是拷贝，所以空间释放也没事
        snprintf(id, 64, "thread-%d", i); // 线程名格式化打印到缓冲区
        int n = pthread_create(&tid, nullptr, routine, id); 
        // 主线程
        if (n == 0)
            tids.push_back(tid);
        else
            continue;
        // sleep(1);
    }

    // 等待线程, 一个个依次回收
    for (int i = 0; i < num; i++)
    {
        int n = pthread_join(tids[i], nullptr);
        if (n == 0)
            std::cout << "等待新线程成功~" << std::endl;
    }

    return 0;
}

#if 0
void *routine(void *args)
{
    pthread_detach(pthread_self());

    int cnt = 5;
    while (cnt--)
    {
        std::cout << "新线程" << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, routine, (void *)"thread-1");
    // pthread_detach(tid);
    // std::cout << "新线程被分离" << std::endl;
    int cnt = 5;
    while (cnt--)
    {
        std::cout << "主线程" << std::endl;
        sleep(1);
    }
    int n = pthread_join(tid, nullptr);
    if (n != 0)
    {
        std::cout << "pthread_join error: " << strerror(n) << std::endl;
    }
    else
    {
        std::cout << "pthread_join success: " << std::endl;
    }


    return 0;
}

#endif

#if 0
class Task
{
public:
    Task(int a, int b) : _a(a), _b(b) {};
    ~Task() {};
    int Execute() { return _a + _b; }

private:
    int _a;
    int _b;
};

class Result
{
public:
    Result(int result) : _result(result) {};
    ~Result() {};
    int GetResult() { return _result; }

private:
    int _result;
};

void *routine(void *args)
{
    Task *t = static_cast<Task *>(args);
    sleep(1);
    Result *res = new Result(t->Execute());
    sleep(1);
    //return res;
    pthread_exit(res);
}

int main()
{
    pthread_t tid;
    Task *t = new Task(2, 3);
    pthread_create(&tid, nullptr, routine, t);

    Result *ret = nullptr;
    pthread_join(tid, (void **)&ret);
    int n = ret->GetResult();
    std::cout << "新线程结束, 结果: " << n << std::endl;

    delete (t);
    delete (ret);
    return 0;
}



void *routine(void *args)
{
    std::string name = static_cast<const char *>(args);
    int cnt = 10;
    while (cnt--)
    {
        std::cout << "新线程名字: " << name << std::endl;
        sleep(1);
    }
    return (void *)10;
}

#endif